package com.tcd.helper.redis;

import com.tcd.utils.AccountUtils;
import com.tcd.utils.JsonUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @ClassName : com.tcd.helper.redis.ZSetRedisHelper
 * @Description : 描述
 * Author : space
 * CreatedDate 2021-05-26 17:14:18
 */
public class ZSetRedisHelper extends RedisHelper{
    public static void addSet(String zsetName, String field, List dataList, Boolean isReplace){
        if (isReplace && redisTemplate.hasKey(zsetName)){
            redisTemplate.delete(zsetName);
        }
        for (Object data : dataList) {
            redisTemplate.opsForZSet().add(zsetName, JsonUtils.objectToJson(data),(Integer) AccountUtils.getFieldVal(data,field));
        }
    }
    public static void addIfAbsentSet(String zsetName,String field, List dataList){
        if (!redisTemplate.hasKey(zsetName)){
            addSet(zsetName,field,dataList,false);
        }
    }
    public static void addSet(String zsetName,String field, Object obj){
        redisTemplate.opsForZSet().add(zsetName,JsonUtils.objectToJson(obj),(Integer)AccountUtils.getFieldVal(obj,field));
    }
    public static void updateSet(String zsetName,String field, Object obj){
        Integer score = (Integer)AccountUtils.getFieldVal(obj,field);
        if (redisTemplate.opsForZSet().count(zsetName,score,score).intValue() < 0){
            System.err.println("修改失败，未找到该数据");
            return;
        }
        deleteSet(zsetName,score);
        addSet(zsetName, field, obj);
    }
    public static void deleteSet(String zsetName,Integer... scores ){
        for (Integer score : scores) {
            redisTemplate.opsForZSet().removeRangeByScore(zsetName,score,score);
        }
    }
    public static List getValSet(String zsetName, Class cls, Integer start, Integer count){
        List list = new ArrayList();
        Set<Object> sets = redisTemplate.opsForZSet().range(zsetName, start, start + count - 1);
        for (Object set : sets) {
            list.add(JsonUtils.jsonToPojo(set.toString(),cls));
        }
        return list;
    }
    public static Integer getValCountSet(String zsetName){
        return redisTemplate.opsForZSet().zCard(zsetName).intValue();
    }
}
